<?php

// 直接アクセスを拒否する
if (!defined("IN_APP"))
	exit("直接アクセスはできません。");

// viewの表示
function viewPage($page) {
	global $SETTINGS;

	$path = $SETTINGS['LOCAL_PATH'] . "view/" . $page . ".view.phtml";	
	include($path);
}

// データベースに接続する
function connectToDb() {
	global $SETTINGS;
	
	// 接続
	$connect = @mysql_connect( $SETTINGS['DB_HOST'], $SETTINGS['DB_USER'], $SETTINGS['DB_PASS'] );
	
	// 接続に成功した
	if ( $connect ) {
		// データベースを選択	
		mysql_select_db( $SETTINGS['DB_NAME'], $connect );
		mysql_query("set names 'utf8'", $connect);
		
		return $connect;
	}
	// 接続に失敗した場合、エラーで終了
	else {
		exit("データベース接続に失敗しました");		
	}
}

// ユーザーが存在しているのか
function userExists($dbConnection, $user_id) {
	$user_id = mysql_real_escape_string($user_id);
	
	$query = "SELECT user_id FROM users ";
	$query.= "WHERE user_id = '{$user_id}' ";
	$query.= "AND (del_flag <> 'd' OR del_flag IS NULL)";
	
	$result = mysql_query($query, $dbConnection);
	
	if ( !$result ) {
		exit('Invalid query: $query - ' . mysql_error());
	}
	else {
		$row = mysql_fetch_assoc($result);
		
		if (!empty($row['user_id']))
			return true;
		else
			return false;
	}
}

// グループのリーダーのidを取得する
function getLeaderId($dbConnection, $group_id) {
	// リーダーのidを取得する
	$query = sprintf("SELECT owner_id FROM groups WHERE group_id = %s ",
								mysql_real_escape_string($group_id));
	$query.= "AND (del_flag <> 'd' OR del_flag IS NULL)";
		
	$result = mysql_query($query, $dbConnection);
	
	$row = mysql_fetch_assoc($result);
	
	// リーダーのidを返す
	return $row['owner_id'];
}

// ユーザーがグループのリーダーかどうかを調べる
function isLeader($dbConnection, $group_id, $user_id) {
	// リーダーのidを取得する
	$query = sprintf("SELECT owner_id FROM groups WHERE group_id = %s ",
								mysql_real_escape_string($group_id));
	$query .= "AND (del_flag <> 'd' OR del_flag IS NULL)";
		
	$result = mysql_query($query, $dbConnection);
	
	$row = mysql_fetch_assoc($result);
	
	// ユーザーのidと比較する
	if ($row['owner_id'] == $user_id)
		return true;
	else
		return false;
}

// ユーザーidを取得する
function getUserId($dbConnection, $username) {
	$username = mysql_real_escape_string($username);
	
	$query = "SELECT user_id FROM users ";
	$query.= "WHERE twitter_username = '{$username}' ";
	$query .= "AND (del_flag <> 'd' OR del_flag IS NULL)";
	
	$result = mysql_query($query, $dbConnection);
	
	if ( !$result ) {
		exit('Invalid query: $query - ' . mysql_error());
	}
	else {
		$row = mysql_fetch_assoc($result);
		
		if (!empty($row['user_id']))
			return $row['user_id'];
		else
			return false;
	}
}

// 全角スペースも含めて、trimする関数
function mb_trim($str) {
	$str = str_replace("　", " ", $str);
	return trim($str);
}


// グループ内の呼び名があれば、それを返して、なければプロフィールのユーザー名を返す
function getUserName($dbConnection, $groupId, $user_id) {
	$groupId = mysql_real_escape_string($groupId);
	$user_id = mysql_real_escape_string($user_id);
	
	$query = "SELECT name,member_nickname FROM users ";
	$query.= "INNER JOIN group_members ON users.user_id = group_members.user_id ";
	$query.= "WHERE users.user_id = {$user_id} AND group_members.group_id = {$groupId} ";
	$query.= "AND (users.del_flag <> 'd' OR users.del_flag IS NULL) ";
	$query.= "AND (group_members.del_flag <> 'd' OR group_members.del_flag IS NULL)";
	
	$result = mysql_query($query, $dbConnection);
	
	if ( !$result ) {
		exit('Invalid query: $query - ' . mysql_error());
	}
	else {
		$row = mysql_fetch_assoc($result);
		
		if (!empty($row['member_nickname']))
			return $row['member_nickname'];
		else
			return $row['name'];
	}
}

//　ツイッターのユーザー名を取得する
function getTwitterUsername($dbConnection, $user_id) {
	$user_id = mysql_real_escape_string($user_id);
	
	$query = "SELECT twitter_username FROM users ";
	$query.= "WHERE user_id = $user_id ";
	$query.= "AND (del_flag <> 'd' OR del_flag IS NULL)";
	
	$result = mysql_query($query, $dbConnection);
	
	if ( !$result ) {
		exit('Invalid query: $query - ' . mysql_error());
	}
	else {
		$row = mysql_fetch_assoc($result);
		
		return $row['twitter_username'];
	}
}

//　グループの名前を取得する
function getGroupName($dbConnection, $groupId) {
	$group_id = mysql_real_escape_string($groupId);
	
	$query = "SELECT title FROM groups ";
	$query.= "WHERE group_id = '{$group_id}' ";
	$query .= "AND (del_flag <> 'd' OR del_flag IS NULL)";
	
	$result = mysql_query($query, $dbConnection);
	
	if ( !$result ) {
		exit('Invalid query: $query - ' . mysql_error());
	}
	else {
		$row = mysql_fetch_assoc($result);
		
		if (!empty($row['title']))
			return $row['title'];
		else
			return false;
	}
}

// グループを表示する順番を読み込む
function getGroupOrder($dbConnection, $groupId) {
	$group_id = mysql_real_escape_string($groupId);
	
	$query = "SELECT user_id FROM group_members ";
	$query.= "WHERE group_id = '{$group_id}' ";
	$query.= "AND (del_flag <> 'd' OR del_flag IS NULL) ";
	$query.= "ORDER BY sort_order ASC";
	
	$result = mysql_query($query, $dbConnection);
	
	if ( !$result ) {
		exit('Invalid query: $query - ' . mysql_error());
	}
	else {
		$group_members = array();
		while ($row = mysql_fetch_assoc($result)) {
			array_push($group_members, $row['user_id']);
		}
		
		return $group_members;
	}
}

// 指定された時刻に出席していたユーザーの配列を取得する
function getPresentUsers($dbConnection, $groupId, $timestamp) {
	$performedDate = date("Y-m-d", $timestamp);

	$query = "SELECT user_id, status, time FROM attendance WHERE group_id = {$groupId} AND status = 1 AND date = '{$performedDate}' ";
	$query.= "AND (del_flag <> 'd' OR del_flag IS NULL)";

	$result = mysql_query($query, $dbConnection);

	$presentUsers = array();
	$awayUsers = array();

	while ($row = mysql_fetch_assoc($result)) {
		if ($row['status'] == 1) {
			if (array_search($row['user_id'], $presentUsers) === false &&
				array_search($row['user_id'], $awayUsers) === false) {
					array_push($presentUsers, $row['user_id']);
			}
		}
		else if ($row['status'] == 0) {
			if (array_search($row['user_id'], $presentUsers) === false &&
				array_search($row['user_id'], $awayUsers) === false) {
					array_push($awayUsers, $row['user_id']);
			}
		}
	}
	
	return $presentUsers;
}

// 履歴の値を初期値に戻す
function resetHistoryMemory() {
	unset($_SESSION["history_type"]);
	unset($_SESSION["history_start_date"]);
	unset($_SESSION["history_end_date"]);
	unset($_SESSION["history_user"]);
}

function loginRequired() {
	global $SETTINGS;
	global $MESSAGES;

	if (!LOGGED_IN) {
		$error = $MESSAGES['ACCESS_FORBIDDEN'];
		
		$page_name = "error";
	
		$include_path = $SETTINGS['VIEW_PATH'] . "error/" . $page_name . $SETTINGS['VIEW_NAME'];
		include($include_path);
		exit();
	}
}

//　ログインしていないと終了する
function requireLogin() {
	// ログインしたユーザーのみがアクセスできる
	if (!isset($_SESSION['user_id']))
		exit("ログインしないとアクセスできません。");
}

// エラーページを表示する
function showErrorPage($errorMsg = false) {
	global $tab_name;
	global $page_name;
	global $error;
	
	if ($errorMsg)
		$error = $errorMsg;
	
	$tab_name = "error/";
	$page_name = "error";
}

function selectGroup($group) {
	$_SESSION["group"] = $group;
	resetHistoryMemory();
}

function normalizeJapaneseCharacters($str) {
	$replace_of = array('ｳﾞ','ｶﾞ','ｷﾞ','ｸﾞ',
						'ｹﾞ','ｺﾞ','ｻﾞ','ｼﾞ',
						'ｽﾞ','ｾﾞ','ｿﾞ','ﾀﾞ',
						'ﾁﾞ','ﾂﾞ','ﾃﾞ','ﾄﾞ',
						'ﾊﾞ','ﾋﾞ','ﾌﾞ','ﾍﾞ',
						'ﾎﾞ','ﾊﾟ','ﾋﾟ','ﾌﾟ','ﾍﾟ','ﾎﾟ');
	$replace_by = array('ヴ','ガ','ギ','グ',
						'ゲ','ゴ','ザ','ジ',
						'ズ','ゼ','ゾ','ダ',
						'ヂ','ヅ','デ','ド',
						'バ','ビ','ブ','ベ',
						'ボ','パ','ピ','プ','ペ','ポ');
	$str = str_replace($replace_of, $replace_by, $str);

	$replace_of = array('０','１','２','３',
						'４','５','６','７',
						'８','９');
						
	$replace_by = array('0','1','2','3',
						'4','5','6','7',
						'8','9');
						
	$str = str_replace($replace_of, $replace_by, $str);


	$replace_of = array('Ａ','Ｂ','Ｃ','Ｄ',
						'Ｅ','Ｆ','Ｇ','Ｈ',
						'Ｉ','Ｊ','Ｋ','Ｌ',
						'Ｍ','Ｎ','Ｏ','Ｐ',
						'Ｑ','Ｒ','Ｓ','Ｔ',
						'Ｕ','Ｖ','Ｗ','Ｘ',
						'Ｙ','Ｚ');
						
	$replace_by = array('A','B','C','D',
						'E','F','G','H',
						'I','J','K','L',
						'M','N','O','P',
						'Q','R','S','T',
						'U','V','W','X',
						'Y','Z');
						
	$str = str_replace($replace_of, $replace_by, $str);
	
	$replace_of = array('ａ','ｂ','ｃ','ｄ',
						'ｅ','ｆ','ｇ','ｈ',
						'ｉ','ｊ','ｋ','ｌ',
						'ｍ','ｎ','ｏ','ｐ',
						'ｑ','ｒ','ｓ','ｔ',
						'ｕ','ｖ','ｗ','ｘ',
						'ｙ','ｚ');
						
	$replace_by = array('a','b','c','d',
						'e','f','g','h',
						'i','j','k','l',
						'm','n','o','p',
						'q','r','s','t',
						'u','v','w','x',
						'y','z');
						
	$str = str_replace($replace_of, $replace_by, $str);
	
	$replace_of = array('ｱ','ｲ','ｳ','ｴ','ｵ',
						'ｶ','ｷ','ｸ','ｹ','ｺ',
						'ｻ','ｼ','ｽ','ｾ','ｿ',
						'ﾀ','ﾁ','ﾂ','ﾃ','ﾄ',
						'ﾅ','ﾆ','ﾇ','ﾈ','ﾉ',
						'ﾊ','ﾋ','ﾌ','ﾍ','ﾎ',
						'ﾏ','ﾐ','ﾑ','ﾒ','ﾓ',
						'ﾔ','ﾕ','ﾖ','ﾗ','ﾘ',
						'ﾙ','ﾚ','ﾛ','ﾜ','ｦ',
						'ﾝ','ｧ','ｨ','ｩ','ｪ',
						'ｫ','ヵ','ヶ','ｬ','ｭ',
						'ｮ','ｯ','､','｡','ｰ',
						'｢','｣','ﾞ','ﾟ');
	$replace_by = array('ア','イ','ウ','エ','オ',
						'カ','キ','ク','ケ','コ',
						'サ','シ','ス','セ','ソ',
						'タ','チ','ツ','テ','ト',
						'ナ','ニ','ヌ','ネ','ノ',
						'ハ','ヒ','フ','ヘ','ホ',
						'マ','ミ','ム','メ','モ',
						'ヤ','ユ','ヨ','ラ','リ',
						'ル','レ','ロ','ワ','ヲ',
						'ン','ァ','ィ','ゥ','ェ',
						'ォ','ヶ','ヶ','ャ','ュ',
						'ョ','ッ','、','。','ー',
						'「','」','”','');		
	$str = str_replace($replace_of, $replace_by, $str);
	
	return $str;
}

?>